package com.kang.gaklibrary.controller;

import com.kang.gaklibrary.config.value.ConfigValue;
import com.kang.gaklibrary.model.Goods;
import com.kang.gaklibrary.model.Plan;
import com.kang.gaklibrary.model.User;
import com.kang.gaklibrary.model.UserFriend;
import com.kang.gaklibrary.service.GoodsService;
import com.kang.gaklibrary.service.PlanService;
import com.kang.gaklibrary.service.UserFriendService;
import com.kang.gaklibrary.service.UserService;
import com.kang.gaklibrary.util.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;        // User实体类服务
    @Autowired
    private PlanService planService;        // Plan实体类服务
    @Autowired
    private UserFriendService userFriendService; // UserFriend实体类服务
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private JavaMailSender mailSender;      // 邮件发送
    @Autowired
    private ConfigValue configValue;        // 使用yaml文件中配置好的一些值

    private static int selectFlag = 0;

    // 检查账户登录
    public User check(HttpServletRequest request){
        User user = null;
        HttpSession session = request.getSession(false);
        if (session != null){
            user = (User) session.getAttribute("user");
        }
        return user;
    }

    // 检索商品
    public void selectGoods(HttpServletRequest request, Model model){
        // 标记检索
        selectFlag = 1;

    }


    @RequestMapping("/")
    public String index(HttpServletRequest request, Model model){
        User user = check(request);
        if (user == null){
            model.addAttribute("userFlag",0);
        }
//        System.out.println("...........................................................................");
        // 检索商品
        List<Goods> goodsList = goodsService.selectAllGoods();
        System.out.println("...........................................................................");
        System.out.println("书籍数目：" + goodsList.size());
        model.addAttribute("indexGoodsList", goodsList);

        if (user != null){
            model.addAttribute("userFlag",1);
        }
        return "index";
    }


    @RequestMapping("/userIndex")
    public String userIndex(HttpServletRequest request, Model model){
        User user = (User) request.getSession(false).getAttribute("user");
        List<UserFriend> userFriends = userFriendService.selectAllFriendById(user.getUserId());
        model.addAttribute("personList", userFriends);
        if(user != null) {
            return "userIndex";
        }else {
            return "login";
        }
    }


    @RequestMapping("/login")
    public String login2(){
        return "login";
    }


    @PostMapping( "/userLogin")
    @ResponseBody
    public void userLogin(@RequestParam("userId") String userId, @RequestParam("password") String password,
                            HttpServletRequest request, Model model, HttpServletResponse response){
        User user = userService.userLogin(userId);
        if (user != null && user.getUserPwd().equals(password)){
            request.getSession().setAttribute("user", user);
            List<UserFriend> userFriends = userFriendService.selectAllFriendById(user.getUserId());
            model.addAttribute("personList", userFriends);
            model.addAttribute("flag", 0);
            System.out.println("用户 " + userId + "已登录。。。");
            try {
                response.sendRedirect(configValue.getIndexUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            model.addAttribute("flag", 1);
            System.out.println("密码错误。。。。。。。。。。。");
            try {
                response.sendRedirect(configValue.getLoginUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping(value = "register")
    public String toUserRegister(){
        return "register";
    }


    @PostMapping("/sendQqVerify")
    @ResponseBody
    public boolean getQqVerify(String qq, Model model, HttpServletRequest request){
        model.addAttribute("begin", 0);
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("752397499@qq.com");
        mailMessage.setTo(qq + "@qq.com");
        mailMessage.setSubject("GAK账户注册");
        String code = VerifyCode.generateVerifyCode(6);
        StringBuffer val = new StringBuffer("您获得的验证码是：" + code + "  感谢您的使用！");
        mailMessage.setText(val.toString());
        mailSender.send(mailMessage);
        model.addAttribute("begin", 1);
        request.getSession().setAttribute("verify", code);
        request.getSession().setAttribute("verifyQq", qq);
        System.out.println(qq + "...........................................................");
        model.addAttribute("qq",qq);
        return true;
    }


    @PostMapping("/userRegister")
    public String userRegister(@RequestParam("userId") String id, @RequestParam("userPwd") String password,
                               @RequestParam("userQq") String qq, @RequestParam("code") String code, HttpServletRequest request, Model model){

        if (code != null && request.getSession().getAttribute("verify").equals(code)
                && request.getSession().getAttribute("verifyQq").equals(qq)){
            User user = new User();
            user.setUserId(id);
            user.setUserPwd(password);
            user.setUserQq(qq);
            int i = userService.insertUser(user);
            request.getSession().setAttribute("user", user);
            return "login";
        }else {

        }
        if (code != null){
            if (request.getSession().getAttribute("verify").equals(code)){
                if (request.getSession().getAttribute("verifyQq").equals(qq)){
                    User user = new User();
                    user.setUserId(id);
                    user.setUserPwd(password);
                    user.setUserQq(qq);
                    int i = userService.insertUser(user);
                    request.getSession().setAttribute("user", user);
                    return "login";
                }else {
                    model.addAttribute("qqError", 1);
                    return "register";
                }
            }else {
                model.addAttribute("codeError", 1);
                return "register";
            }
        }
        return "register";
    }


    @RequestMapping("/userLoginOut")
    public String userLoginOut(HttpServletRequest request){
        User user = check(request);
        if (user != null){
            System.out.println("用户：" + user.getUserId() + "退出登录。。。");
            request.getSession().invalidate();
        }
        return "login";
    }


    @RequestMapping("/plan")
    public String index(Model model, HttpServletRequest request){
        User user = check(request);
        if (user != null){
            List<Plan> plans = planService.selectAllByQq(user.getUserQq());
            model.addAttribute("itemList",plans);
            return "plan";
        }else {
            return "login";
        }
    }

    @RequestMapping("/delete")
    public void delete(Integer id, String qq, Model model, HttpServletRequest request
            , HttpServletResponse response){
        planService.deleteByPrimaryKey(id);
        try {
            response.sendRedirect(configValue.getPlanUrl());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/increase")
    public void increase(String plan, Model model, HttpServletRequest request
    , HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        planService.insertSelective(plan, user.getUserQq());
//        request.getRequestDispatcher(configValue.getPlanUrl());
        try {
            response.sendRedirect(configValue.getPlanUrl());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
